package com.woniuxy.background.controller;

import com.github.pagehelper.PageInfo;
import com.woniuxy.background.advice.SysLog;
import com.woniuxy.background.common.RestResult;
import com.woniuxy.background.pojo.Commont;
import com.woniuxy.background.service.CommontService;
import com.woniuxy.background.service.GoodsService;
import com.woniuxy.background.service.UsersService;
import com.woniuxy.background.vo.CmtVO;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/cmt")
public class CommontController {

    @Autowired
    private CommontService commontService;
    @Autowired
    private UsersService usersService;
    @Autowired
    private GoodsService goodsService;


    @GetMapping("/list")
    @ResponseBody
    @RequiresPermissions("cmt:cmt:list")
    public RestResult list(@RequestParam(value = "page",defaultValue = "1",required = false) Integer currentPage,
                           @RequestParam(value = "limit",defaultValue = "5",required = false) Integer pageSize,
                           CmtVO vo){
        System.out.println(vo);
        List<Commont> commonts = commontService.queryCommontByPage(currentPage,pageSize,vo);
        PageInfo pageInfo = new PageInfo(commonts);
        List<Commont> list = new ArrayList<>();
        for (Commont c : commonts){
            c.setUser(usersService.findById(c.getUserId()));
            c.setGoods(goodsService.selectByPrimaryKey(c.getGoodsId()));
            list.add(c);
        }
        pageInfo.setList(list);
        return RestResult.success(pageInfo);
    }

    @DeleteMapping("/deleteCmt/{keys}")
    @ResponseBody
    @SysLog(value = "删除多个评论")
    @RequiresPermissions("cmt:cmt:delete")
    public RestResult deleteUser(@PathVariable("keys") String keys){
        String[] arr = keys.split(",");
        List<Integer> list = new ArrayList();
        for (String id : arr) {
            list.add(Integer.parseInt(id));
        }
        try {
            commontService.batchDeleteCmt(list);
        } catch (Exception e) {
            e.printStackTrace();
            return RestResult.failed("删除失败");
        }
        return RestResult.success("删除成功");
    }

    @DeleteMapping("/delete/{cid}")
    @ResponseBody
    @SysLog(value = "删除评论")
    @RequiresPermissions("cmt:cmt:delete")
    public RestResult deleteUser(@PathVariable("cid")int cid){
        try {
            commontService.deleteByPrimaryKey(cid);
        }catch (Exception e){
            e.printStackTrace();
            return RestResult.failed("删除失败！");
        }
        return RestResult.success("删除成功！");
    }
}
